<?php
namespace Tongcheng\Controller;
use Think\Controller;
use Think\Think;
class Notify2Controller extends CommonController {
    public function index11111111111(){
        $xmlObj = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'],'SimpleXMLElement',LIBXML_NOCDATA);//simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']); //解析回调数据
        file_put_contents('ordersuccess.txt',$xmlObj.PHP_EOL,FILE_APPEND);
        $appid = (string)$xmlObj->appid;//微信appid
        $mch_id = (string)$xmlObj->mch_id;  //商户号
        $nonce_str = (string)$xmlObj->nonce_str;//随机字符串
        $sign = (string)$xmlObj->sign;//签名
        $result_code = (string)$xmlObj->result_code;//业务结果
        $openid = (string)$xmlObj->openid;//用户标识
        $is_subscribe = (string)$xmlObj->is_subscribe;//是否关注公众帐号
        $trace_type = (string)$xmlObj->trade_type;//交易类型，JSAPI,NATIVE,APP
        $bank_type = (string)$xmlObj->bank_type;//付款银行，银行类型采用字符串类型的银行标识。
        $total_fee = (string)$xmlObj->total_fee;//订单总金额，单位为分
        $fee_type = (string)$xmlObj->fee_type;//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
        $transaction_id = (string)$xmlObj->transaction_id;//微信支付订单号
        $out_trade_no = (string)$xmlObj->out_trade_no;//商户订单号
        $attach = (string)$xmlObj->attach;//商家数据包，原样返回
        $time_end = (string)$xmlObj->time_end;//支付完成时间
        $cash_fee = (string)$xmlObj->cash_fee;
        $return_code = (string)$xmlObj->return_code;

        //根据订单号获取订单
        $shoporder = M('ShopOrder')->where('out_trade_no = '.$out_trade_no)->select();
        if(empty($shoporder)){
            echo "fail";
        }
        //返回成功
        if('SUCCESS'==$return_code && 'SUCCESS' == $result_code){
            $map['out_trade_no'] = $out_trade_no;
            $data['transaction_id'] = $transaction_id;
            $data['is_pay'] = 1;
            $data['id'] = $shoporder[0]['id'];
            $type = $_GET['type'];
            switch(intval($type)){
                case 1://购买图书
                    break;
                case 2://购买闲置
                    break;
                case 3://用户充值
                    //修改订单状态
                    M('ShopOrder')->where('id = '.$shoporder[0]['id'])->save($data);
                    //修改用户余额
                    $member = M('Member')->where('id = '.$shoporder[0]['uid'])->select();
                    if(empty($member)){
                        echo 'fail';
                    }else{
                        $yue = floatval($member[0]['yu_e_num']) + floatval($shoporder[0]['price']);
                        $update['yu_e_num'] = $yue;
                        M('Member')->where('id = '.$member[0]['id'])->save($update);
                        echo 'success';
                    }
                    break;
            }
        }else{
            echo 'fail';
        }

    }
    public function renewShop(){
        $xmlObj = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']); //解析回调数据
        $appid = (string)$xmlObj->appid;//微信appid
        $mch_id = (string)$xmlObj->mch_id;  //商户号
        $nonce_str = (string)$xmlObj->nonce_str;//随机字符串
        $sign = (string)$xmlObj->sign;//签名
        $result_code = (string)$xmlObj->result_code;//业务结果
        $openid = (string)$xmlObj->openid;//用户标识
        $is_subscribe = (string)$xmlObj->is_subscribe;//是否关注公众帐号
        $trace_type = (string)$xmlObj->trade_type;//交易类型，JSAPI,NATIVE,APP
        $bank_type = (string)$xmlObj->bank_type;//付款银行，银行类型采用字符串类型的银行标识。
        $total_fee = (string)$xmlObj->total_fee;//订单总金额，单位为分
        $fee_type = (string)$xmlObj->fee_type;//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
        $transaction_id = (string)$xmlObj->transaction_id;//微信支付订单号
        $out_trade_no = (string)$xmlObj->out_trade_no;//商户订单号
        $attach = (string)$xmlObj->attach;//商家数据包，原样返回
        $time_end = (string)$xmlObj->time_end;//支付完成时间
        $cash_fee = (string)$xmlObj->cash_fee;
        $return_code = (string)$xmlObj->return_code;

        $map['out_trade_no'] = $out_trade_no;
        $data['transaction_id'] = $transaction_id;

        $data['pay_time'] = date("Y-m-d H:i:s",strtotime($time_end));
        $data['is_pay'] = 1;
        M("ShopOrder")->where($map)->save($data);

        $info = M("ShopOrder")->where($map)->find();
        $eq['shop_id'] = $info['shop_id'];
        $new['is_pay'] = 1;
        $new['status'] = 1;
        $new['join_end_time'] = date("Y-m-d H:i:s", strtotime("+ {$info['join_days']}days"));
        M("Shop")->where($eq)->save($new);
    }
    public function reserveOrder(){
        $xmlObj = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']); //解析回调数据
        $appid = (string)$xmlObj->appid;//微信appid
        $mch_id = (string)$xmlObj->mch_id;  //商户号
        $nonce_str = (string)$xmlObj->nonce_str;//随机字符串
        $sign = (string)$xmlObj->sign;//签名
        $result_code = (string)$xmlObj->result_code;//业务结果
        $openid = (string)$xmlObj->openid;//用户标识
        $is_subscribe = (string)$xmlObj->is_subscribe;//是否关注公众帐号
        $trace_type = (string)$xmlObj->trade_type;//交易类型，JSAPI,NATIVE,APP
        $bank_type = (string)$xmlObj->bank_type;//付款银行，银行类型采用字符串类型的银行标识。
        $total_fee = (string)$xmlObj->total_fee;//订单总金额，单位为分
        $fee_type = (string)$xmlObj->fee_type;//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
        $transaction_id = (string)$xmlObj->transaction_id;//微信支付订单号
        $out_trade_no = (string)$xmlObj->out_trade_no;//商户订单号
        $attach = (string)$xmlObj->attach;//商家数据包，原样返回
        $time_end = (string)$xmlObj->time_end;//支付完成时间
        $cash_fee = (string)$xmlObj->cash_fee;
        $return_code = (string)$xmlObj->return_code;

        $data = array();
        $data['is_pay'] = 1;
        $data['pay_time'] = date("Y-m-d H:i:s",strtotime($time_end));
        $data['state'] = 1;
        M('takeout_ydorder')->where(array('ydcode'=>$out_trade_no))->save($data);

    }
    public function takeoutOrder(){
        $xmlObj = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']); //解析回调数据
        $appid = (string)$xmlObj->appid;//微信appid
        $mch_id = (string)$xmlObj->mch_id;  //商户号
        $nonce_str = (string)$xmlObj->nonce_str;//随机字符串
        $sign = (string)$xmlObj->sign;//签名
        $result_code = (string)$xmlObj->result_code;//业务结果
        $openid = (string)$xmlObj->openid;//用户标识
        $is_subscribe = (string)$xmlObj->is_subscribe;//是否关注公众帐号
        $trace_type = (string)$xmlObj->trade_type;//交易类型，JSAPI,NATIVE,APP
        $bank_type = (string)$xmlObj->bank_type;//付款银行，银行类型采用字符串类型的银行标识。
        $total_fee = (string)$xmlObj->total_fee;//订单总金额，单位为分
        $fee_type = (string)$xmlObj->fee_type;//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
        $transaction_id = (string)$xmlObj->transaction_id;//微信支付订单号
        $out_trade_no = (string)$xmlObj->out_trade_no;//商户订单号
        $attach = (string)$xmlObj->attach;//商家数据包，原样返回
        $time_end = (string)$xmlObj->time_end;//支付完成时间
        $cash_fee = (string)$xmlObj->cash_fee;
        $return_code = (string)$xmlObj->return_code;

        $data = array();
        $data['is_pay'] = 1;
        $data['state'] = 2;
        $data['pay_time'] = date("Y-m-d H:i:s",strtotime($time_end));
        M('takeout_order')->where(array('sh_ordernum'=>$out_trade_no))->save($data);

    }


    /* 微信支付完成，回调地址url方法  xiao_notify_url() */
    public function index(){
        $post = $this->post_data();    //接受POST数据XML个数
        $post_data = $this->xml_to_array($post);   //微信支付成功，返回回调地址url的数据：XML转数组Array
        file_put_contents('ordersuccess.txt',time().':'.json_encode($post_data).PHP_EOL,FILE_APPEND);
        $postSign = $post_data['sign'];
        unset($post_data['sign']);

        /* 微信官方提醒：
         *  商户系统对于支付结果通知的内容一定要做【签名验证】,
         *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
         *  防止数据泄漏导致出现“假通知”，造成资金损失。
         */
        ksort($post_data);// 对数据进行排序
        $str = $this->ToUrlParams($post_data);//对数组数据拼接成key=value字符串
        $user_sign = strtoupper(md5($post_data));   //再次生成签名，与$postSign比较

        if($post_data['return_code']=='SUCCESS'&&$postSign){//
            /*
            * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
            * 其次，订单已经为ok的，直接返回SUCCESS
            * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
            */
//            if($order_status['order_status']=='ok'){
//                $this->return_success();
//            }else{
//                $updata['order_status'] = 'ok';
//                if(M('home_order','xxf_witkey_')->where($where)->save($updata)){
//                    $this->return_success();
//                }
//            }
//            $post_data['out_trade_no']=$_GET['out_trade_no'];
//            $post_data['transaction_id'] = '1';
            //根据订单号获取订单
            $shoporder = M('ShopOrder')->where('out_trade_no = "'.$post_data['out_trade_no'].'"')->select();
            file_put_contents('ordersuccess.txt',time().':获取type'.json_encode($shoporder[0]).PHP_EOL,FILE_APPEND);
            if(empty($shoporder[0])){
                echo "fail";
            }
            //判断是否已修改订单
            if(1 == $shoporder[0]['is_pay']){
                $this->return_success();
            }
//            $data['out_trade_no'] = $post_data['out_trade_no'];
            $data['transaction_id'] = $post_data['transaction_id'];;
            $data['is_pay'] = 1;
            $data['id'] = $shoporder[0]['id'];
            $type = $post_data['type'];
            file_put_contents('ordersuccess.txt',time().':获取type'.$type.PHP_EOL,FILE_APPEND);
            switch(intval($type)){
                case 1://购买图书
                    file_put_contents('ordersuccess.txt',time().':'.json_encode($post_data).PHP_EOL,FILE_APPEND);
                    $member = M('Member')->where('uid = '.$shoporder[0]['uid'])->select();
                    if(empty($member[0])){
                        echo 'fail';
                    }else{
                        //修改用户的活动押金和冻结押金
                        //活动押金
                        $yajin = $member['yajin'];
                        //冻结押金
                        $dong_jie_yajin = $member['dong_jie_yajin'];
                        //1.如果活动押金大于书本的押金则 冻结押金=原冻结+书本押金，活动押金=原活动-书本押金，交付押金0
                        if(floatval($yajin)>=floatval($shoporder[0]['yuanjia'])){
                            $dong_jie_yajin = floatval($dong_jie_yajin)+floatval($shoporder[0]['yuanjia']);
                            $yajin = floatval($yajin)-floatval($shoporder[0]['yuanjia']);

                        }else{
                            //2,如果活动押金小于书本押金  冻结押金=原冻结+书本押金 ，活动押金=0，交付押金=书本押金-活动押金
                            $dong_jie_yajin = floatval($dong_jie_yajin)+floatval($shoporder[0]['yuanjia']);
                            $yajin = 0;
                        }
                        $result = M('Member')->where('uid = '.$shoporder[0]['uid'])->save(array('yajin'=>$yajin,'dong_jie_yajin'=>$dong_jie_yajin));
                        if($result){
                            $this->return_success();
                        }else{
                            echo fail;
                        }
                    }
                    break;
                case 2://购买闲置
                    break;
                case 3://用户充值
                    file_put_contents('ordersuccess.txt',time().':'.json_encode($post_data).PHP_EOL,FILE_APPEND);
                    //修改订单状态
                    M('ShopOrder')->where('id = '.$shoporder[0]['id'])->save($data);
                    //修改用户余额
                    $member = M('Member')->where('uid = '.$shoporder[0]['uid'])->select();
                    if(empty($member[0])){
                        echo 'fail';
                    }else{
                        $yue = floatval($member[0]['yu_e_num']) + floatval($shoporder[0]['price']);
                        $update['yu_e_num'] = $yue;
                        M('Member')->where('uid = '.$member[0]['uid'])->save($update);
                        file_put_contents('ordersuccess.txt',time().':余额增加成功'.PHP_EOL,FILE_APPEND);
                        $this->return_success();
                    }
                    break;
            }
        }else{
            echo '微信支付失败';
        }
    }


    private function return_success(){
        $return['return_code'] = 'SUCCESS';
        $return['return_msg'] = 'OK';
        $xml_post = '<xml>
                    <return_code>'.$return['return_code'].'</return_code>
                    <return_msg>'.$return['return_msg'].'</return_msg>
                    </xml>';
        echo $xml_post;exit;
    }

    private function post_data(){
        $receipt = $_REQUEST;
        if($receipt==null){
            $receipt = file_get_contents("php://input");
            if($receipt == null){
                $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
            }
        }
        return $receipt;
    }

    /**
     * 将xml转为array
     * @param string $xml
     * return array
     */
    public function xml_to_array($xml){
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        libxml_disable_entity_loader($disableLibxmlEntityLoader);
        return $data;
    }
    /**
     * 将参数拼接为url: key=value&key=value
     * @param $params
     * @return string
     */
    public function ToUrlParams( $params ){
        $string = '';
        if( !empty($params) ){
            $array = array();
            foreach( $params as $key => $value ){
                $array[] = $key.'='.$value;
            }
            $string = implode("&",$array);
        }
        return $string;
    }
}